<template>
  <div class="mod-config">
    <table-view ref="view"
                :searchAttrs="searchAttrs"
                :primaryKey="primaryKey"
                :listApiName="listApiName"
                :deleteApiName="deleteApiName"
                :saveAuthName="saveAuthName"
                :deleteAuthName="deleteAuthName"
                :templateDownloadApiName="templateDownloadApiName"
                :importApiName="importApiName"
                :showAttrs="showAttrs"
                :exportApiName="exportApiName"
                :deep-multi-add="true"
                :sumInfo='sumInfo'
    >
      <template v-slot:header>
        <el-button size="small" type="warning" @click="openChartDialog">图表</el-button>
      </template>
      <template v-slot:foot="{scope}">

<!--        <el-tooltip class="item" effect="dark" content="修改" placement="bottom"-->
<!--                    :hide-after="1800" :open-delay="800">-->
<!--          <el-button type="primary" icon="el-icon-edit" size="small"-->
<!--                     @click="addOrUpdateHandle(R.path(['row', primaryKey], scope))"></el-button>-->
<!--        </el-tooltip>-->
      </template>

<!--      -->
    </table-view>
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <productinfo-add-or-update v-if="productInfoVisible" ref="productInfo"></productinfo-add-or-update>
    <client-info-add-or-update v-if="clientInfoVisible" ref="clientInfo"></client-info-add-or-update>
    <!--  图表对话框  -->
    <normal-chart-dialog ref="charDialog"
                         :chartSearchObj="chartSearchObj"
                         :commitChartSearch="commitChartSearch"
    >
      <template v-slot:chart="{chart}">
        <chart ref="chart"></chart>
      </template>
    </normal-chart-dialog>
    <el-dialog
      title="批量入库"
      :visible.sync="deepDialogVisible"
      width="100%"
      :before-close="handleClose">

      <el-form
        :model="dataForm"
        ref="dataForm"
        label-width="120px"
        label-position="left"
        style="margin-left:30px"
      >
        <el-form-item label="所属业务人员" style="width: 400px">
          <el-select v-model="businessId" clearable filterable placeholder="请选择所属业务人员"  >
            <el-option
              v-for="item in businessInfoList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="入库时间" style="width: 400px">
          <el-date-picker
            v-model="putInTime"
            align="right"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="供应商" style="width: 400px">
          <el-select v-model="supplierId" clearable filterable placeholder="请选择" @change="initPurchaseProductInfoList()"  >
            <el-option
              v-for="item in supplierInfoList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="供应商出库单号" style="width: 400px">
          <el-input  v-model="supplierTickerNo"  placeholder="供应商出库单号" ></el-input>

        </el-form-item>
      </el-form>




      <el-table
        :data="tableListData"
        border
        style="display: inline-block">

        <el-table-column
          prop="purchaseProductId"
          label="采购订单编号"
          align="center"
          width="150"
        >
          <template slot-scope="scope">
            <el-select v-model="scope.row.purchaseProductId" @change="changeOrderByOrderDetailId(scope.row.purchaseProductId,scope.$index)" clearable filterable placeholder="请选择">
              <el-option
                v-for="item in purchaseContractList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column
          prop="productId"
          label="产品名称"
          align="center"
          width="150"
        >
          <template slot-scope="scope">
            <el-select v-model="scope.row.productId" clearable filterable placeholder="请选择">
              <el-option
                v-for="item in productInfoList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column
          prop="customerRequire"
          label="规格描述"
          align="center"
          width="200"
        >
          <template slot-scope="scope">
            <el-input  v-model="scope.row.customerRequire"  placeholder="规格描述" ></el-input>
          </template>
        </el-table-column>

        <el-table-column
          prop="boxPackText"
          label="箱唛描述"
          align="center"
          width="200"
        >
          <template slot-scope="scope">
            <el-input  v-model="scope.row.boxPackText"  placeholder="箱唛描述" ></el-input>
          </template>
        </el-table-column>


        <el-table-column
          prop="productWeight"
          label="克重"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            <el-input-number controls-position="right" size="small" :min="0"  v-model="scope.row.productWeight" placeholder="克重"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column
          prop="boxSupplyWay"
          label="包装方式"
          align="center"
          width="100"
        >
          <template slot-scope="scope">
            <el-select v-model="scope.row.boxSupplyWay" clearable filterable placeholder="包装" @change="numberChanged(scope.$index)">
              <el-option label="纸箱" :value=0>纸箱</el-option>
            </el-select>
          </template>
        </el-table-column>


        <el-table-column
          prop="boxZhiNumber"
          label="箱只"
          controls-position="right"
          align="center"
        >
          <template slot-scope="scope">
            <el-input-number controls-position="right" size="small" :min="0"  v-model="scope.row.boxZhiNumber" placeholder="箱只" @change="numberChanged(scope.$index)"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          prop="boxNumber"
          label="箱数"
          controls-position="right"
          align="center"
        >
          <template slot-scope="scope">
            <el-input-number controls-position="right" size="small" :min="0"  v-model="scope.row.boxNumber" placeholder="箱数" @change="numberChanged(scope.$index)"></el-input-number>
          </template>
        </el-table-column>



        <el-table-column
          prop="scrapNumber"
          label="零头"
          controls-position="right"
          align="center"
        >
          <template slot-scope="scope">
            <el-input-number controls-position="right" size="small" :min="0"  v-model="scope.row.scrapNumber" placeholder="零头" @change="numberChanged(scope.$index)"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column
          prop="countProductNumber"
          label="总数量"
          controls-position="right"
          align="center"
        >
          <template slot-scope="scope">
            <el-input-number controls-position="right" size="small" :min="0"  v-model="scope.row.countProductNumber" placeholder="总数量"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column
          prop="remark"
          label="备注"
          align="center"
        >
          <template slot-scope="scope">
            <el-input  v-model="scope.row.remark"  placeholder="备注" ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="location"
          label="存放位置"
          align="center"
        >
          <template slot-scope="scope">

            <el-select v-model="scope.row.location" clearable filterable placeholder="位置" >
              <el-option label="A" value='A'>A</el-option>
              <el-option label="B" value='B'>B</el-option>
              <el-option label="C" value='C'>C</el-option>
              <el-option label="D" value='D'>D</el-option>
              <el-option label="E" value='E'>E</el-option>
              <el-option label="F" value='F'>F</el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column
          fixed="right"
          label="操作"
          width="130px"
        >
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="addRow(scope.$index, tableListData)"
              type="success"
              icon="el-icon-plus"
              circle>
            </el-button>
            <el-button v-if="tableListData.length>1"
                       @click.native.prevent="deleteRow(scope.$index, tableListData)"
                       icon="el-icon-delete"
                       type="danger"
                       circle>
            </el-button>

          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deepDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import AddOrUpdate from './productputinstorage-add-or-update'
import tableView from '@/components/tableView'
import basicMixins from '@/utils/commonViewMixins'
import ProductinfoAddOrUpdate from '@/views/modules/product/productinfo-add-or-update'
import chart from '@/views/charts/product/productInCategoryWeightChart'
import ClientInfoAddOrUpdate from '@/views/modules/client/clientinfo-add-or-update.vue'
import {mRequest} from '@/utils/request'

export default {
  mixins: [basicMixins],
  data() {
    return {
      chartSearchObj: {
        dataForm: {
          dateTimeRange: []
        },
        config: {
          dateTimeRange: {
            type: 'date',
            clearable: true,
            dateType: 'daterange',
            label: '时间范围'
          }
        }
      },
      deepDialogVisible: false,
      tableListData: [{
        purchaseProductId: '',
        productId: '',
        clientId: '',
        location: '',
        customerRequire: '',
        remark: '',
        productWeight: 0,
        boxSupplyWay: 0,
        trayLayerNumber: 0,
        trayEachZhiNumber: 0,
        boxNumber: 0,
        boxZhiNumber: 0,
        scrapNumber: 0,
        countProductNumber: 0,
        weightCount: 0
      }],
      dataForm: {},
      putInTime: '',
      supplierId: '',
      businessId: '',
      businessInfoList: [],
      supplierTickerNo: '',
      purchaseContractNo: '',
      purchaseContractList: [],
      orderDetailList: [],
      productInfoList: [],
      supplierInfoList: [],
      clientInfoList: [],
      clientInfoVisible: false,
      productInfoVisible: false,
      sumInfo:{countProductNumber: 'countProductNumber'},
      searchAttrs: {
        productNo: {
          placeholder: '请选择产品',

        },
        businessId: {
          type: 'autoComplete',
          placeholder: '请输入业务员',
          querySearchApiName: 'systemApi/listSaleUser'
        },
        supplierId: {
          placeholder: '供应商名称',
          type: 'autoComplete',
          querySearchApiName: 'supplierApi/getSupplierList'
        },
        dateTimeRange: {
          type: 'date',
          dateType: 'daterange',
          clearable: true
        }
      },
      primaryKey: 'id',
      listApiName: 'productApi/listProductPutInStorage',
      deleteApiName: 'productApi/deleteProductPutInStorage',
      saveAuthName: 'product:productputinstorage:save',
      deleteAuthName: 'product:productputinstorage:delete',
      templateDownloadApiName: 'productApi/templateDownloadProductPutInStorage',
      //getProductInStorageExport
      exportApiName: 'productApi/getProductInStorageExport',
      importApiName: 'productApi/importProductPutInStorage',
      showAttrs: {
        clientContractNo: {label: '业务合同编号',width: 200},
        productNo: {
          label: '产品编号',
          type: 'linkLabel',
          routerName: 'product-product-info-all',
          searchKey: 'productNo',
          width:130
        },
        customerRequire:{
          label: '规格描述',
        },
        boxZhiNumber: {label: '箱只'},
        boxNumber: {label: '箱数'},
        scrapNumber: {label: '零头'},
        countProductNumber: {label: '总数量', type: 'tag',width:130},
        businessName: {label: '业务人员', width: 140},
        supplierName: {
          label: '供应商名称',
          type: 'linkLabel',
          routerName: 'client-clientinfo',
          searchKey: 'clientName'
        },
        // },
        remark: {label: '备注'},
        putInTime: {label: '日期', type: 'date',width:110},
        location: {label: '存放位置'},
        productWeight: {label: '克数', type: 'tag'},

        // status: {
        //   label: '状态',
        //   type: 'radio',
        //   items: [
        //     {value: 0, text: '禁用', tagType: 'danger'},
        //     {value: 1, text: '正常'}
        //   ]
        // }
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      }
    }
  },
  methods: {
    initMulti(){
      this.initPurchaseProductInfoList()
      this.initProductInfoList()
      this.initSupplierList()
      this.initBusinessInfoList()
      this.putInTime = ''
      this.supplierId = ''
      this.supplierTickerNo = ''
      this.businessId = ''
      this.tableListData = [{
        purchaseProductId: '',
        productId: '',
        customerRequire: '',
        clientId: '',
        location: '',
        remark: '',
        productWeight: 0,
        boxSupplyWay: 0,
        trayLayerNumber: 0,
        trayEachZhiNumber: 0,
        trayNumber: 0,
        boxNumber: 0,
        boxZhiNumber: 0,
        scrapNumber: 0,
        countProductNumber: 0,
        weightCount: 0
      }]
    },
    handleClose(done){
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    addRow(index, rows) {
      rows.push({
        purchaseProductId: '',
        productId: '',
        customerRequire: '',
        clientId: '',
        location: '',
        remark: '',
        productWeight: 0,
        boxSupplyWay: 0,
        trayLayerNumber: 0,
        trayEachZhiNumber: 0,
        trayNumber: 0,
        boxNumber: 0,
        boxZhiNumber: 0,
        scrapNumber: 0,
        countProductNumber: 0,
        weightCount: 0,
      });
    },
    initOrderDetailList() {
      mRequest('orderApi/getOrderDetailList', {}, (res) => {
        this.orderDetailList = this.R.pathOr([], ['data', 'list'], res)
      })
    },
    initProductInfoList() {
      mRequest('productApi/getProductInfoList', {}, (res) => {
        this.productInfoList = this.R.pathOr([], ['data', 'list'], res)
      })
    },
    initClientInfoList(attrName = 'clientId') {
      mRequest('clientApi/getClientList', {}, (res) => {
        this.clientInfoList = this.R.pathOr([], ['data', 'list'], res)
      })
    },
    initSupplierList() {
      mRequest('supplierApi/getSupplierList', {}, (res) => {
        this.supplierInfoList = this.R.pathOr([], ['data', 'list'], res)
      })
    },
    //InitBusinessInfoList
    initBusinessInfoList() {
      mRequest('systemApi/listSaleUser', {}, (res) => {
        this.businessInfoList = this.R.pathOr([], ['data', 'list'], res)
      })
    },
    initPurchaseProductInfoList() {
      mRequest('purchaseApi/getPurchaseProductInfoList', {'supplierId':this.supplierId}, (res) => {
        this.purchaseContractList = this.R.pathOr([], ['data', 'list'], res)
      })
    },
    changeSupplierId() {
      this.supplierInfoList()
    },
    changeOrderByOrderDetailId(purchaseProductId,index) {
      if (this.R.isNil(purchaseProductId) || this.R.equals('', purchaseProductId)) {
        this.tableListData[index].purchaseProductId = ''
        this.tableListData[index].productId = ''
        this.tableListData[index].customerRequire = ''
        this.tableListData[index].productWeight = 0
        this.tableListData[index].boxSupplyWay = 0
        this.tableListData[index].trayLayerNumber = 0
        this.tableListData[index].trayEachZhiNumber = 0
        this.tableListData[index].boxNumber = 0
        this.tableListData[index].boxZhiNumber = 0
        this.tableListData[index].scrapNumber = 0
        this.tableListData[index].countProductNumber = 0
        this.tableListData[index].weightCount = 0
        return
      }
      mRequest('purchaseApi/purchasePartInfo', {id:purchaseProductId}, (data) => {
        const purchaseProduct = this.R.pathOr({}, ['data', 'purchaseProduct'], data)
        this.tableListData[index].productId = purchaseProduct.productId
        this.tableListData[index].productWeight = purchaseProduct.productWeight
        this.tableListData[index].boxSupplyWay = this.R.propOr(0, 'boxSupplyWay',purchaseProduct)
        this.tableListData[index].customerRequire = this.R.propOr('', 'customerRequire',purchaseProduct)

      })
    },
    numberChanged(index) {
      const packType = this.R.propOr(0, 'boxSupplyWay', this.tableListData[index])
      const productWeight = this.R.propOr(0, 'productWeight', this.tableListData[index])

      if (packType !== 1) {
        const boxNumber = this.R.propOr(0, 'boxNumber', this.tableListData[index])
        const boxZhiNumber = this.R.propOr(0, 'boxZhiNumber', this.tableListData[index])
        const scrapNumber = this.R.propOr(0, 'scrapNumber', this.tableListData[index])
        this.tableListData[index].countProductNumber = boxNumber * boxZhiNumber + scrapNumber
      } else if (packType === 1) {
        const trayLayerNumber = this.R.propOr(0, 'trayLayerNumber', this.tableListData[index])
        const trayEachZhiNumber = this.R.propOr(0, 'trayEachZhiNumber', this.tableListData[index])
        const trayNumber = this.R.propOr(0, 'trayNumber', this.tableListData[index])
        const scrapNumber = this.R.propOr(0, 'scrapNumber', this.tableListData[index])

        // this.dataForm.countProductNumber = trayLayerNumber * trayEachZhiNumber * trayNumber + scrapNumber
      //  this.tableListData[index].countProductNumber = trayLayerNumber * trayEachZhiNumber  + scrapNumber
        this.tableListData[index].countProductNumber = trayLayerNumber * trayEachZhiNumber * trayNumber  + scrapNumber
      }
      this.tableListData[index].weightCount = this.tableListData[index].countProductNumber * productWeight
    },
    dataFormSubmit() {
      mRequest('productApi/multipleSaveProductPutInStorage', {
        'putInTime':this.putInTime,
        'supplierId':this.supplierId,
        'businessId':this.businessId,
        'supplierTickerNo':this.supplierTickerNo,
        'tableListData':this.tableListData
      }, (data) => {
        if (data.data.code === 0) {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500
          })
        } else {
          this.$message.error(data.data.msg)
        }
        this.getDataList()
        this.deepDialogVisible = false
      })
    },
    openProductInfoDialog(cb) {
      this.productInfoVisible = true
      this.$nextTick(() => {
        if (!this.R.isNil(this.$refs.productInfo)) {

          this.$refs.productInfo.init(null, {status: 1}, cb)
        }
      })
    },
    openClientInfoDialog(cb) {
      this.clientInfoVisible = true
      this.$nextTick(() => {
        if (!this.R.isNil(this.$refs.clientInfo)) {
          this.$refs.clientInfo.init(null, {status: 1}, cb)
        }
      })
    },
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        if (!this.R.isNil(this.$refs.addOrUpdate)) {
          this.$refs.addOrUpdate.init(id)
        }
      })
    }
  },
  components: {
    ProductinfoAddOrUpdate,
    ClientInfoAddOrUpdate,
    AddOrUpdate,
    tableView,
    chart
  }
}
</script>
